package com.example.douyin.zhibo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.view.animation.CycleInterpolator;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.douyin.R;
import com.example.douyin.adapter.GiftAdapter;
import com.example.douyin.adapter.MessageAdapter;
import com.example.douyin.databinding.ActivityZhiboBinding;
import com.example.douyin.db.DBUtils;
import com.example.lib_base_mvvm.baseMVVM.BaseView.BaseActivity;
import com.example.lib_base_mvvm.entity.GiftEntity;
import com.example.lib_base_mvvm.entity.MessageEntity;
import com.example.lib_base_mvvm.entity.ResultEntity;
import com.example.lib_base_mvvm.entity.User;
import com.example.lib_base_mvvm.entity.VideoEntity;

import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import top.littlefogcat.danmakulib.danmaku.Danmaku;
import top.littlefogcat.danmakulib.danmaku.DanmakuManager;

@Route(path = "/app/ZhiboActivity")
public class ZhiboActivity extends BaseActivity<ActivityZhiboBinding,ZhiboViewModel> {
    @Autowired
    VideoEntity.DataBean video;

    List<GiftEntity.DataBean> gifts = new ArrayList<>();
    GiftAdapter giftAdapter;
    int gift_index = -1;//下标给-1，防止未选中礼物，可以点击发送
    private GiftControl giftControl;
    //最好的方法是，当我们注册新账号时，创建账户信息，
    private User user;//获取当前的账户信息

    List<MessageEntity> messages = new ArrayList<>();
    MessageAdapter messageAdapter;
    private DanmakuContext danmakuContext;//烈焰弹幕上下文

    @Override
    public int bindLayout() {
        return R.layout.activity_zhibo;
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        //显示视频播放器
        initGsy();
        //显示左上角的用户信息
        initUser();
        //初始化礼物列表
        initGift();
        initUserMoney();//初始化账户信息
        initMessage();//初始化消息列表
        initDanmu();
        giftControl = new GiftControl(dataBinding.layoutGift,this);
        dataBinding.ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //点击小爱心
        dataBinding.ivDianzan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataBinding.ksgView.addLikeImages(R.drawable.ic_xihuanred,R.drawable.ic_fasong,R.drawable.ic_gift);
                dataBinding.ksgView.addFavor();
            }
        });
        //点击礼物
        dataBinding.ivGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //1.显示礼物框
                dataBinding.clGift.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(ZhiboActivity.this, R.anim.anmi_in);
                dataBinding.clGift.startAnimation(animation);
                //加载礼物数据
            }
        });
        //关闭礼物框
        dataBinding.giftClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataBinding.clGift.setVisibility(View.GONE);
                Animation animation = AnimationUtils.loadAnimation(ZhiboActivity.this, R.anim.anmi_out);
                dataBinding.clGift.startAnimation(animation);
            }
        });
        //点击发送礼物
        dataBinding.giftSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(gift_index<0){
                    ToastUtils.showLong("您还未选中心仪的礼物，请进行选择");
                    return;
                }
                //余额比较---稍后写
                if(user.getBalance()<gifts.get(gift_index).getPrice()){
                    ToastUtils.showLong("当前余额不足，请充值");
                    return;
                }
                sendGift(gift_index);
            }
        });
        dataBinding.tvChong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //可以把User作为参数传过去，这样，支付界面就不需要查询数据了
                //不传任何参数，支付界面自行查询
                ARouter.getInstance().build("/app/ZhiboPayActivity").withSerializable("user",user).navigation(ZhiboActivity.this,300);
                //相当于startActivityForResult();
            }
        });
        //点击文本框，弹出输入框
        dataBinding.tvMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataBinding.clInput.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(ZhiboActivity.this, R.anim.anmi_in);
                animation.setInterpolator(new BounceInterpolator());
                dataBinding.clInput.startAnimation(animation);
                //给etinput添加焦点
                dataBinding.etInput.requestFocus();
            }
        });
        dataBinding.etSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = dataBinding.etInput.getText().toString();
                if(string.isEmpty()){
                    ToastUtils.showLong("还没填写内容哟");
                    return;
                }
                messages.add(new MessageEntity(SPUtils.getInstance().getString("username"),string));
                messageAdapter.notifyDataSetChanged();
                dataBinding.etInput.setText("");
                dataBinding.clInput.setVisibility(View.GONE);
                //发送简单弹幕
                DanmakuManager.getInstance().init(ZhiboActivity.this,dataBinding.danmuEasy);
                Danmaku danmaku = new Danmaku();
                danmaku.text = string;
                danmaku.color = "#ffff0000";
                danmaku.size = 50;
                DanmakuManager.getInstance().send(danmaku);
                //发烈焰弹幕
                dataBinding.danmuView.removeAllDanmakus(true);//发送弹幕时调用，不让第二次发送时，会把第一次发送的值再次显示
                BaseDanmaku baseDanmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);//从右向左滚动的弹幕
                baseDanmaku.text = string;
                baseDanmaku.textSize = 60;
                baseDanmaku.textColor = Color.YELLOW;
                baseDanmaku.borderColor = Color.GREEN;
                baseDanmaku.setTime(1000);
                dataBinding.danmuView.addDanmaku(baseDanmaku);
                dataBinding.danmuView.start();


            }
        });


    }

    private void initDanmu() {
        dataBinding.danmuView.enableDanmakuDrawingCache(false);
        dataBinding.danmuView.clear();
        dataBinding.danmuView.removeAllDanmakus(true);//清屏

        //实例化上下文
        danmakuContext = DanmakuContext.create();

        dataBinding.danmuView.prepare(new BaseDanmakuParser() {
            @Override
            protected IDanmakus parse() {
                return new Danmakus();
            }
        },danmakuContext);
    }

    private void initMessage() {
        messageAdapter = new MessageAdapter(R.layout.item_message,messages);
        dataBinding.rvMessage.setAdapter(messageAdapter);
        dataBinding.rvMessage.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.rvMessage.scrollToPosition(messages.size()-1);//自动滚动到最新的一行
    }

    private void initUserMoney() {
        //判断当前账号是否存在，不存在，创建新账号
        String username = SPUtils.getInstance().getString("username");
        user =  DBUtils.getInstance().getMoneyDao().queryByName(username);
        if(user==null){
            user = new User(username,0);
            DBUtils.getInstance().getMoneyDao().insertUser(user);
        }
        dataBinding.tvMoney.setText(user.getBalance()+"逗比");
    }

    ImageView imageView;//发送礼物的图片
    private void sendGift(int index) {
        user.setBalance(user.getBalance()-gifts.get(gift_index).getPrice());
        DBUtils.getInstance().getMoneyDao().updateUser(user);
        dataBinding.tvMoney.setText(user.getBalance()+"逗比");
        giftControl.loadGift(gifts.get(gift_index));
        if(imageView==null){//首次发送
            imageView = new ImageView(this);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(200, 200);
            imageView.setLayoutParams(params);
            Glide.with(this).load(gifts.get(gift_index).getGiftpath()).into(imageView);
            dataBinding.clZhibo.addView(imageView);//为了显示图片，将图片添加动cl中
        }else{
            imageView.setVisibility(View.VISIBLE);//第一次发送礼物完成后图片隐藏了，之后在发送直接显示就行
            Glide.with(this).load(gifts.get(gift_index).getGiftpath()).into(imageView);
        }

        //添加动画效果
        int width = getWindowManager().getDefaultDisplay().getWidth();//获取屏幕宽度
        int height = getWindowManager().getDefaultDisplay().getHeight();//获取屏幕高度
        ObjectAnimator translationX = ObjectAnimator.ofFloat(imageView, "translationX", 0, width, width / 2 - 100);//X轴位移
        ObjectAnimator translationY = ObjectAnimator.ofFloat(imageView, "translationY", 0, height / 5, height / 2 - 100);//Y轴位移

        ObjectAnimator rotation = ObjectAnimator.ofFloat(imageView, "rotation", 0, 360);//旋转
        rotation.setInterpolator(new CycleInterpolator(2));

        ObjectAnimator scaleX = ObjectAnimator.ofFloat(imageView, "scaleX", 1, 2, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(imageView, "scaleY", 1, 2, 1);

        AnimatorSet set = new AnimatorSet();
        set.play(translationX).with(translationY).before(rotation).before(scaleX).before(scaleY);
        set.setDuration(3000);
        set.start();
        //动画结束后，将图片隐藏
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                imageView.setVisibility(View.GONE);
            }
        });

    }

    private void initGift() {

        giftAdapter = new GiftAdapter(R.layout.item_gift,gifts);
        dataBinding.rvGift.setAdapter(giftAdapter);
        dataBinding.rvGift.setLayoutManager(new GridLayoutManager(this,4));

        viewModel.gift();
        viewModel.giftSuccess.observe(this, new Observer<GiftEntity>() {
            @Override
            public void onChanged(GiftEntity entity) {
                if(entity.getCode()==200){
                    gifts.clear();
                    gifts.addAll(entity.getData());
                    giftAdapter.notifyDataSetChanged();
                }else{
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.giftFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });

        giftAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                //记录一下当前下标--获取礼物
                gift_index = position;
                Glide.with(ZhiboActivity.this).load(gifts.get(position).getGiftpath()).into(dataBinding.giftChecked);
            }
        });


    }

    private void initUser() {
        Glide.with(this).load(video.getHeadpath()).into(dataBinding.ivUsername);
        dataBinding.tvUsername.setText(video.getAuthname());
        if(video.getGuanzhu()==1){
            dataBinding.tvGuanzhu.setText("粉丝");
            dataBinding.tvGuanzhu.setBackground(getDrawable(R.drawable.bg_cl_user));
        }else{
            //不修改原来的值
            //可以去进行关注的操作
            dataBinding.tvGuanzhu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    viewModel.guanzhu(video.getAuthname());//执行网络请求
                }
            });
        }
    }

    private void initGsy() {
        dataBinding.gsy.getBackButton().setVisibility(View.GONE);
        dataBinding.gsy.getStartButton().setVisibility(View.GONE);
        dataBinding.gsy.setUp(video.getVideopath(),true,"");
        dataBinding.gsy.startPlayLogic();
    }

    @Override
    public void initData() {
        viewModel.guanzhuSuccess.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                if(entity.getCode()==200){
                    ToastUtils.showLong(entity.getMessage());
                    dataBinding.tvGuanzhu.setText("粉丝");
                    dataBinding.tvGuanzhu.setBackground(getDrawable(R.drawable.bg_cl_user));
                }else{
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.guanzhuFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
    }

    @Override
    public Class<ZhiboViewModel> getViewModel() {
        return ZhiboViewModel.class;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==300&&resultCode==301){
            int balance = data.getExtras().getInt("balance");
            dataBinding.tvMoney.setText(balance+"元");
            user.setBalance(balance);
        }
    }
}